package com.manage.modules.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.manage.common.config.RuoYiConfig;
import com.manage.common.core.domain.entity.SysUser;
import com.manage.common.utils.SecurityUtils;
import com.manage.framework.config.ServerConfig;
import com.manage.modules.domain.TBaseFaultPhoto;
import com.manage.modules.dto.TBaseFaultSelectDto;
import com.manage.modules.dto.TBaseFaultSelectReturnDto;
import com.manage.modules.service.ITBaseFaultPhotoService;
import com.manage.modules.utils.UploadUtil;
import com.manage.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.manage.modules.bo.TBaseFaultAddBo;
import com.manage.modules.bo.TBaseFaultQueryBo;
import com.manage.modules.bo.TBaseFaultEditBo;
import com.manage.modules.domain.TBaseFault;
import com.manage.modules.mapper.TBaseFaultMapper;
import com.manage.modules.vo.TBaseFaultVo;
import com.manage.modules.service.ITBaseFaultService;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 故障信息Service业务层处理
 *
 * @author wx
 * @date 2021-08-18
 */
@Service
public class TBaseFaultServiceImpl extends ServiceImpl<TBaseFaultMapper, TBaseFault> implements ITBaseFaultService {
    @Resource
    private ITBaseFaultPhotoService faultPhotoService;
    @Resource
    private ServerConfig serverConfig;
    @Resource
    private ISysUserService sysUserService;


    @Override
    public List<TBaseFaultSelectReturnDto> queryBySelectDto(TBaseFaultSelectDto selectDto) {
        LambdaQueryWrapper<TBaseFault> lqw = Wrappers.lambdaQuery();
        lqw.eq(selectDto.getEquipHistoryId()!=null,TBaseFault::getEquipHistoryId,selectDto.getEquipHistoryId());
        lqw.select(TBaseFault::getFaultId,TBaseFault::getFaultCode,TBaseFault::getEquipHistoryId,TBaseFault::getStationIdC);
        List<TBaseFault> list = list(lqw);
        List<TBaseFaultSelectReturnDto> dtoList = list.stream()
                .map(any -> BeanUtil.toBean(any, TBaseFaultSelectReturnDto.class))
                .collect(Collectors.toList());
        return dtoList;
    }

    @Override
    public TBaseFaultVo queryById(Long faultId) {
        TBaseFault db = this.baseMapper.selectById(faultId);
        // 查询图片
        List<TBaseFaultPhoto> photoList = faultPhotoService.findByFaultId(db.getFaultId());
        // 加上路径
        for (TBaseFaultPhoto faultPhoto : photoList) {
            faultPhoto.setUrl(serverConfig.getUrl() + faultPhoto.getUrl());
            faultPhoto.setLocal(RuoYiConfig.getProfile() + faultPhoto.getLocal());
        }
        TBaseFaultVo baseFaultVo = BeanUtil.toBean(db, TBaseFaultVo.class);
        baseFaultVo.setTBaseFaultPhotoList(photoList);
        List<SysUser> userList = sysUserService.listIdAndNickname();
        baseFaultVo.setReportPeopleName(sysUserService.getNickNameByUserId(baseFaultVo.getReportUserId(), userList));
        baseFaultVo.setApprovePeopleName(sysUserService.getNickNameByUserId(baseFaultVo.getApproveUserId(), userList));
        return baseFaultVo;
    }


    @Override
    public List<TBaseFaultVo> queryList(TBaseFaultQueryBo bo) {
        LambdaQueryWrapper<TBaseFault> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getStationIdC()), TBaseFault::getStationIdC, bo.getStationIdC());
        lqw.eq(bo.getEquipHistoryId() != null, TBaseFault::getEquipHistoryId, bo.getEquipHistoryId());
        lqw.eq(bo.getFaultTypeId() != null, TBaseFault::getFaultTypeId, bo.getFaultTypeId());
        lqw.eq(StrUtil.isNotBlank(bo.getFaultCode()), TBaseFault::getFaultCode, bo.getFaultCode());
        lqw.ge(bo.getFaultStartTime() != null, TBaseFault::getFaultStartTime, bo.getFaultStartTime());
        lqw.le(bo.getFaultEndTime() != null, TBaseFault::getFaultEndTime, bo.getFaultEndTime());
        lqw.eq(bo.getFaultState() != null, TBaseFault::getFaultState, bo.getFaultState());


        List<TBaseFaultVo> voList = entity2Vo(this.list(lqw));

        List<SysUser> userList = sysUserService.listIdAndNickname();
        // 设置数据
        for (TBaseFaultVo tBaseFaultVo : voList) {
            tBaseFaultVo.setReportPeopleName(sysUserService.getNickNameByUserId(tBaseFaultVo.getReportUserId(), userList));
            tBaseFaultVo.setApprovePeopleName(sysUserService.getNickNameByUserId(tBaseFaultVo.getApproveUserId(), userList));
        }

        return voList;
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TBaseFaultVo> entity2Vo(Collection<TBaseFault> collection) {
        List<TBaseFaultVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TBaseFaultVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TBaseFault> page = (Page<TBaseFault>) collection;
            Page<TBaseFaultVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TBaseFaultAddBo bo) {
        TBaseFault add = BeanUtil.toBean(bo, TBaseFault.class);
        // 设置上报人就为当前用户
        add.setReportUserId(SecurityUtils.getUserId());
        add.setReportTime(new Date());
        // 由平台新增得初始状态统一为已读
        add.setFaultState(2L);
        validEntityBeforeSave(add);
        this.save(add);

        List<TBaseFaultPhoto> tBaseFaultPhotoList = bo.getSitePhotoUrlList();
        // 只存相对路径
        setUrl(tBaseFaultPhotoList, add.getFaultId());
        faultPhotoService.saveBatch(tBaseFaultPhotoList);

        // 删除照片
        faultPhotoService.delete(bo.getDeletePhotoList());
        return true;
    }

    @Override
    public Boolean updateByEditBo(TBaseFaultEditBo bo) {
        TBaseFault update = BeanUtil.toBean(bo, TBaseFault.class);
        validEntityBeforeSave(update);

        // 设置当前用户为审批人
        update.setApproveUserId(SecurityUtils.getUserId());
        update.setApproveTime(new Date());

        List<TBaseFaultPhoto> tBaseFaultPhotoList = bo.getSitePhotoUrlList();
        // 只存相对路径
        setUrl(tBaseFaultPhotoList, update.getFaultId());
        faultPhotoService.saveOrUpdateBatch(tBaseFaultPhotoList);

        // 删除照片
        faultPhotoService.delete(bo.getDeletePhotoList());
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TBaseFault entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        // 先删除照片
        faultPhotoService.deleteByFaultIds(ids);

        return this.removeByIds(ids);
    }

    /**
     * 路径修正
     */
    private void setUrl(List<TBaseFaultPhoto> tBaseFaultPhotoList, Long faultId) {
        // 只存相对路径
        for (TBaseFaultPhoto tBaseFaultPhoto : tBaseFaultPhotoList) {
            tBaseFaultPhoto.setFaultId(faultId);
            tBaseFaultPhoto.setUrl(UploadUtil.getUrlByDelete(tBaseFaultPhoto.getUrl(), serverConfig.getUrl()));
            tBaseFaultPhoto.setLocal(UploadUtil.getUrlByDelete(tBaseFaultPhoto.getLocal(), RuoYiConfig.getProfile()));
        }
    }
}
